package com.ruoyi.project.channel.channelOrder.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.AddressUtils;
import com.ruoyi.common.utils.GoogleAuthenticatorUtils;
import com.ruoyi.common.utils.SMSUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.channel.businessCashChange.domain.BusinessCashChange;
import com.ruoyi.project.channel.businessCashChange.service.IBusinessCashChangeService;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.businessInfoOrder.domain.BusinessInfoOrder;
import com.ruoyi.project.channel.businessInfoOrder.service.IBusinessInfoOrderService;
import com.ruoyi.project.channel.channelUserInfo.service.IChannelUserInfoService;
import com.ruoyi.project.channel.payerPayType.domain.PayerPayType;
import com.ruoyi.project.channel.payerPayType.service.IPayerPayTypeService;
import com.ruoyi.project.channel.vwBusinessCashStat.domain.VwBusinessCashStat;
import com.ruoyi.project.channel.vwBusinessCashStat.service.IVwBusinessCashStatService;
import com.ruoyi.project.pay.PayConfig;
import com.ruoyi.project.pay.PayServiceImpl;
import com.ruoyi.project.system.user.domain.UserRole;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.aspectj.weaver.loadtime.Aj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.channelOrder.service.IChannelOrderService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 通道订单信息操作处理
 *
 * @author ruoyi
 * @date 2019-04-09
 */
@Controller
@RequestMapping("/channel/channelOrder")
public class ChannelOrderController extends BaseController {
    private String prefix = "channel/channelOrder";

    @Autowired
    private IChannelOrderService channelOrderService;
    @Autowired
    private PayServiceImpl payService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IPayerPayTypeService payerPayTypeService;
    @Autowired
    private IChannelUserInfoService channelUserInfoService;
    @Autowired
    private IVwBusinessCashStatService vwBusinessCashStatService;
    @Autowired
    private IBusinessCashChangeService businessCashChangeService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IBusinessInfoOrderService businessInfoOrderService;
    @Autowired
    private PayConfig payConfig;
    private static final Logger log = LoggerFactory.getLogger(ChannelOrderController.class);

    @RequiresPermissions("channel:channelOrder:view")
    @GetMapping()
    public String channelOrder(ModelMap mmap) {
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        mmap.put("roleKey", roleKey);
        mmap.put("proxys", userService.selectProxyBusinessList(new User()));
        mmap.put("channels", userService.selectChannelList(new User()));

        PayerPayType search = new PayerPayType();
        search.setPayerUserName("系统自带");
        List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(search);
        mmap.put("payerPayTypes", payerPayTypes);
        return prefix + "/channelOrder";
    }

    @RequiresPermissions("channel:channelOrder:view")
    @GetMapping("/params")
    @ResponseBody
    public AjaxResult channelOrderParams() {
        HashMap<String, Object> mmap = new HashMap<>();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        mmap.put("roleKey", roleKey);
        mmap.put("proxys", userService.selectProxyBusinessList(new User()));
        mmap.put("channels", userService.selectChannelList(new User()));

        PayerPayType search = new PayerPayType();
        search.setPayerUserName("系统自带");
        List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(search);
        mmap.put("payerPayTypes", payerPayTypes);
        return AjaxResult.success("success", mmap);
    }

    @RequiresPermissions("channel:channelOrder:view")
    @GetMapping("/red")
    public String channelOrderRed(ModelMap mmap) {
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        mmap.put("roleKey", roleKey);
        mmap.put("proxys", userService.selectProxyBusinessList(new User()));
        mmap.put("channels", userService.selectChannelList(new User()));

        PayerPayType search = new PayerPayType();
        search.setPayerUserName("系统自带");
        List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(search);
        mmap.put("payerPayTypes", payerPayTypes);
        return prefix + "/channelOrderRed";
    }

    /**
     * 查询通道订单列表
     */
    @RequiresPermissions("channel:channelOrder:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ChannelOrder channelOrder) {
        startPage();
        // 取身份信息
        User user = getSysUser();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        List<ChannelOrder> list = new ArrayList<ChannelOrder>();
        if (roleKey.equals("channel")) {
            channelOrder.setChannelUserId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("mall")) {
            channelOrder.setBusinessId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("agent") || roleKey.equals("salesman")) {
            channelOrder.setAgentUserId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        }  else if (roleKey.equals("group")) {
            channelOrder.getParams().put("groupUserId", user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("admin") || roleKey.equals("admin2") || roleKey.equals("salesView")) {
            list = channelOrderService.selectOrderListNormal(channelOrder);
        }
        return getDataTable(list);
    }

    /**
     * 查询通道订单列表
     */
    @RequiresPermissions("channel:channelOrder:list")
    @PostMapping("/list/success")
    @ResponseBody
    public TableDataInfo listSuccess(ChannelOrder channelOrder) {
        startPage();
        // 取身份信息
        User user = getSysUser();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        channelOrder.getParams().put("payed", "111");
        List<ChannelOrder> list = new ArrayList<ChannelOrder>();
        if (roleKey.equals("channel")) {
            channelOrder.setChannelUserId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("mall")) {
            channelOrder.setBusinessId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("agent") || roleKey.equals("salesman")) {
            channelOrder.setAgentUserId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("admin") || roleKey.equals("admin2") || roleKey.equals("salesView")) {
            list = channelOrderService.selectOrderListNormal(channelOrder);
        }
        return getDataTable(list);
    }

    /**
     * 异常订单
     */
    @RequiresPermissions("channel:channelOrder:list")
    @GetMapping("/eorder")
    public String eorder(ModelMap mmap) {
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        mmap.put("roleKey", roleKey);
        return prefix + "/eorder";
    }

    /**
     * 查询异常通道订单列表
     */
    @RequiresPermissions("channel:channelOrder:list")
    @PostMapping("/listerror")
    @ResponseBody
    public TableDataInfo listerror(ChannelOrder channelOrder) {
        startPage();
        // 取身份信息
        User user = getSysUser();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        List<ChannelOrder> list = new ArrayList<ChannelOrder>();
        if (roleKey.equals("channel")) {
            channelOrder.setChannelUserId(user.getUserId());
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        } else if (roleKey.equals("mall")) {
            channelOrder.setBusinessId(user.getUserId());
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        } else if (roleKey.equals("agent")) {
            channelOrder.setAgentUserId(user.getUserId());
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        } else if (roleKey.equals("admin") || roleKey.equals("admin2")) {
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        }
        return getDataTable(list);
    }

    /**
     * 导出通道订单列表
     */
    @RequiresPermissions("channel:channelOrder:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ChannelOrder channelOrder) {
        // 取身份信息
        User user = getSysUser();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        List<ChannelOrder> list = new ArrayList<ChannelOrder>();
        if (roleKey.equals("channel")) {
            channelOrder.setChannelUserId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("mall")) {
            channelOrder.setBusinessId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("agent")) {
            channelOrder.setAgentUserId(user.getUserId());
            list = channelOrderService.selectOrderListNormal(channelOrder);
        } else if (roleKey.equals("admin") || roleKey.equals("admin2")) {
            list = channelOrderService.selectOrderListNormal(channelOrder);
        }
        ExcelUtil<ChannelOrder> util = new ExcelUtil<ChannelOrder>(ChannelOrder.class);
        return util.exportExcel(list, "channelOrder");
    }

    /**
     * 导出通道订单列表
     */
    @RequiresPermissions("channel:channelOrder:export")
    @PostMapping("/exportError")
    @ResponseBody
    public AjaxResult exportError(ChannelOrder channelOrder) {
        // 取身份信息
        User user = getSysUser();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        List<ChannelOrder> list = new ArrayList<ChannelOrder>();
        if (roleKey.equals("channel")) {
            channelOrder.setChannelUserId(user.getUserId());
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        } else if (roleKey.equals("mall")) {
            channelOrder.setBusinessId(user.getUserId());
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        } else if (roleKey.equals("agent")) {
            channelOrder.setAgentUserId(user.getUserId());
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        } else if (roleKey.equals("admin") || roleKey.equals("admin2")) {
            list = channelOrderService.selectChannelOrderErrorList(channelOrder);
        }
        ExcelUtil<ChannelOrder> util = new ExcelUtil<ChannelOrder>(ChannelOrder.class);
        return util.exportExcel(list, "channelOrder");
    }

    /**
     * 新增通道订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存通道订单
     */
    @RequiresPermissions("channel:channelOrder:add")
    @Log(title = "通道订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ChannelOrder channelOrder) {
        return toAjax(channelOrderService.insertChannelOrder(channelOrder));
    }

    /**
     * 新增保存通道订单
     */
    @Log(title = "通道订单无需登录,需要md5验证", businessType = BusinessType.INSERT)
    @PostMapping("/add/production")
    @ResponseBody
    public AjaxResult addSaveProduction(ChannelOrder channelOrder) {
        return toAjax(channelOrderService.insertChannelOrder(channelOrder));
    }

    /**
     * 修改通道订单
     */
    @GetMapping("/edit/{orderId}")
    public String edit(@PathVariable("orderId") String orderId, ModelMap mmap) {
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        mmap.put("channelOrder", channelOrder);
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        mmap.put("roleKey", roleKey);
        return prefix + "/edit";
    }

    /**
     * 修改通道订单
     */
    @GetMapping("/editRed/{orderId}")
    public String editRed(@PathVariable("orderId") String orderId, ModelMap mmap) {
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        mmap.put("channelOrder", channelOrder);
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        mmap.put("roleKey", roleKey);
        return prefix + "/editRed";
    }

    /**
     * 修改保存通道订单
     */
    @RequiresPermissions("channel:channelOrder:edit")
    @Log(title = "通道订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ChannelOrder channelOrder, String password, String code) {
//        if(password == null || "".equals(password.trim())){
//            return AjaxResult.error("需要补单密码!");
//        }
        // 需输入补单密码
//       if(!channelUserInfoService.matches(password,channelOrder.getChannelUserId())) {
//           return AjaxResult.error("补单密码不正确!");
//       }
//        if(code == null || "".equals(code.trim())){
//            return AjaxResult.error("需要谷歌验证码!");
//        }
//        // 补单需要对应的码商才允许操作
//        User user = userService.selectUserById(channelOrder.getChannelUserId());
//        if(user.getSecretKey()==null || user.getSecretKey().trim().equals("")){
//            return AjaxResult.error("请绑定谷歌验证码后再尝试!");
//        }
        // 需输入补单密码
//        if(!GoogleAuthenticatorUtils.verify(user.getSecretKey(), code)) {
//            String ip = ServletUtils.getRequest().getRemoteHost();
//            String content = "您的账号:" + user.getLoginName() + "输错谷歌验证码，ip地址：" + ip + ";";
//            if (user.getPhonenumber() != null && !"".equals(user.getPhonenumber().trim())) {
//                SMSUtil.sendSms(content, user.getPhonenumber().trim());
//            }
//            return AjaxResult.error("谷歌验证码不正确!");
//        }

        ChannelOrder save = new ChannelOrder();
        save.setOrderId(channelOrder.getOrderId());
        save.setPayAmount(channelOrder.getAmount());
//        save.setAccount(channelOrder.getAccount());
        save.setOrderStatus("2");
        return payService.doUpdate(save, "2");
    }

    /**
     * 修改保存通道订单
     */
    @RequiresPermissions("channel:channelOrder:edit")
    @Log(title = "通道订单", businessType = BusinessType.UPDATE)
    @PostMapping("/addOrder")
    @ResponseBody
    public AjaxResult addOrder(double amount, Long userId, String type) {
        ChannelOrder order = new ChannelOrder();
        order.setBusinessId(userId);
        order.setBusinessFee(BigDecimal.ZERO);
        order.setAmount(BigDecimal.valueOf(amount));
        order.setStatus("0");
        order.setOrderStatus("1");
        order.setPayAmount(BigDecimal.valueOf(amount));
        order.setSubmitTime(new Date());
        order.setRemark("手动上分");
        if (type != null) {
            // 手动上分标志 用来统计时候使用
            order.setDdId(1L);
        }
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(userId);
        if (businessInfo.getOrderPrice() != null) {
            order.setBankName("假人");
        } else {
            order.setBankName("真人");
        }
        order.setSuccessTime(new Date());
        String keyup_prefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String keyup_append = String.valueOf(new Random().nextInt(899999) + 100000);
        String payOrderid = keyup_prefix + keyup_append;//订单号
        order.setPtOrderno(payOrderid);
        order.setChildOrderno(payOrderid);
        order.setPayType("100");
        order.setCreateTime(new Date());
        order.setAgentUserId(getSysUser().getUserId());
        // 记录资金变更记录
        BusinessCashChange change = new BusinessCashChange();
        change.setBusinessId(order.getBusinessId());
        change.setAmount(order.getAmount());
        change.setOpType("1");
        change.setPayType(order.getPayType());
        VwBusinessCashStat searchState = new VwBusinessCashStat();
        searchState.setBusinessId(order.getBusinessId());
        List<VwBusinessCashStat> stats = vwBusinessCashStatService.selectVwBusinessCashStatList(searchState);
        if (stats.size() == 0) {
            change.setPreAmount(BigDecimal.ZERO);
        } else {
            change.setPreAmount(stats.get(0).getAmountSum());
        }
        change.setNextAmount(change.getPreAmount().add(change.getAmount()));
        change.setCreateTime(new Date());
        change.setOrderId(order.getPtOrderno());
        change.setRemark("手动上分");
        channelOrderService.insertChannelOrder(order);
        businessCashChangeService.insertBusinessCashChange(change);
        return AjaxResult.success("success");
    }

    /**
     * 修改保存通道订单
     */
    @RequiresPermissions("channel:channelOrder:edit")
    @Log(title = "通道订单", businessType = BusinessType.UPDATE)
    @PostMapping("/pauseOrder")
    @ResponseBody
    public AjaxResult pauseOrder(Double amount, Long userId, int orderNum, int orderTimes) {
        BusinessInfoOrder order = businessInfoOrderService.selectBusinessInfoOrderById(userId);
        if (order == null) {
            order = new BusinessInfoOrder();
            order.setUserId(userId);
            order.setOrderNum(orderNum);
            order.setOrderTimes(orderTimes);
            order.setOrderPrice(BigDecimal.valueOf(amount));
            businessInfoOrderService.insertBusinessInfoOrder(order);
        } else {
            order.setUserId(userId);
            order.setOrderNum(orderNum);
            order.setOrderTimes(orderTimes);
            order.setOrderPrice(BigDecimal.valueOf(amount));
            businessInfoOrderService.updateBusinessInfoOrder(order);
        }

//        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoByUserId(userId);
//        if (amount == null) {
//            businessInfo.setOrderPrice(null);
//        } else {
//            businessInfo.setOrderPrice(BigDecimal.valueOf(amount));
//        }
//        businessInfoService.updateBusinessInfo(businessInfo);

        return AjaxResult.success("success");
    }

    /**
     * 删除通道订单
     */
    @RequiresPermissions("channel:channelOrder:remove")
    @Log(title = "通道订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(channelOrderService.deleteChannelOrderByIds(ids));
    }

    /**
     * 设置已支付
     */
    @RequiresPermissions("channel:channelOrder:edit")
    @Log(title = "通道订单", businessType = BusinessType.DELETE)
    @PostMapping("/setpay")
    @ResponseBody
    public AjaxResult setpay(String ids) {
        return toAjax(channelOrderService.setpay(ids));
    }

    @GetMapping("/detail/{orderId}")
    public String detail(@PathVariable("orderId") String orderId, ModelMap mmap) {
        ChannelOrder order = channelOrderService.selectChannelOrderById(orderId);
        mmap.put("channelOrder", order);
        return prefix + "/detail";
    }
}
